package org.ngmj.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.ngmj.message.GroupCreateRequestMessage;
import org.ngmj.message.GroupCreateResponseMessage;
import org.ngmj.server.session.Group;
import org.ngmj.server.session.GroupSession;
import org.ngmj.server.session.GroupSessionFactory;
import org.ngmj.server.session.SessionFactory;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        String groupName = groupCreateRequestMessage.getGroupName();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Set<String> members = groupCreateRequestMessage.getMembers();
        Group group = groupSession.createGroup(groupName, members);

        if (group == null) {
            for (String member : members) {
                Channel channel = SessionFactory.getSession().getChannel(member);
                channel.writeAndFlush(new GroupCreateResponseMessage(true, groupName + "群创建成功"));
            }
        } else {
            ctx.channel().writeAndFlush(new GroupCreateResponseMessage(false, groupName + "群已存在"));

        }
    }
}
